package com.facecard;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;


public class Config extends Activity {
    // Debugging
	  CheckBox chkDiscoverable;
	  
	  SharedPreferences prefs;
	  
	  public static final String PREF_DISCOVERABLE = "PREF_DISCOVERABLE";

	  @Override
	  public void onCreate(Bundle icicle) {
	    super.onCreate(icicle);
	    setContentView(R.layout.config);
	   
	    
	    
	    chkDiscoverable = (CheckBox)findViewById(R.id.checkbox_discoverable);

	    //populateSpinners();
	      
	    prefs = getSharedPreferences(Commons.STR_PREFERENCE_NAME, Activity.MODE_PRIVATE);
	    updateUIFromPreferences();

	    Button okButton = (Button) findViewById(R.id.okButton);
	    okButton.setOnClickListener(new View.OnClickListener() {
	      public void onClick(View view) {
	        savePreferences();
	        Config.this.setResult(RESULT_OK);
	        finish();
	      }
	    });

	    Button cancelButton = (Button) findViewById(R.id.cancelButton);
	    cancelButton.setOnClickListener(new View.OnClickListener() {
	      public void onClick(View view) {
	        Config.this.setResult(RESULT_CANCELED);
	        finish();
	      }
	    });
	  }  

	  private void savePreferences() {
		  //int updateIndex = updateFreqSpinner.getSelectedItemPosition();
		  //int minMagIndex = magnitudeSpinner.getSelectedItemPosition();
		  boolean autoUpdateChecked = chkDiscoverable.isChecked();

		  if(autoUpdateChecked)
			  ensureDiscoverable();
		  
		  Editor editor = prefs.edit();
		  editor.putBoolean(PREF_DISCOVERABLE, autoUpdateChecked);
		  //editor.putInt(PREF_UPDATE_FREQ, updateIndex);
		  //editor.putInt(PREF_MIN_MAG, minMagIndex);
		  editor.commit();
	  }
	  
	  private void updateUIFromPreferences() {
		  boolean autoUpChecked = prefs.getBoolean(PREF_DISCOVERABLE, false);
		  /*		  int updateFreqIndex = prefs.getInt(PREF_UPDATE_FREQ, 2);
		  int minMagIndex = prefs.getInt(PREF_MIN_MAG, 0);
		    
		  updateFreqSpinner.setSelection(updateFreqIndex);
		  magnitudeSpinner.setSelection(minMagIndex);
*/		  chkDiscoverable.setChecked(autoUpChecked);
	  }

	    private void ensureDiscoverable() {
	        if(Commons.D) Log.d(Commons.TAG, "ensure discoverable");
	        if (BluetoothAdapter.getDefaultAdapter().getScanMode() !=
	            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
	            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
	            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
	            startActivity(discoverableIntent);
	        }
	    }

}
